/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.handlers.matchers;

import java.util.SortedSet;

import net.sourceforge.wurfl.core.handlers.Handler;
import net.sourceforge.wurfl.core.handlers.matchers.strategy.LDMatcher;
import net.sourceforge.wurfl.core.handlers.matchers.strategy.RISMatcher;
import net.sourceforge.wurfl.core.handlers.matchers.strategy.StringMatcher;
import net.sourceforge.wurfl.core.utils.StringUtils;

import org.apache.commons.lang.text.StrBuilder;

/**
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: VodafoneMatcher.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class VodafoneMatcher extends AbstractMatcher {

	private static final int VODAFONE_TOLLERANCE = 3;

	public VodafoneMatcher(Handler handler) {
		super(handler);
	}

	/**
	 * If UA contains "Nokia" or "Sony" applies RIS at first slash after "Nokia" or "Sony". As falllback applies LD(3).
	 */
	protected String lookForMatchingUserAgent(SortedSet userAgentsSet, String userAgent) {

		String match = null;
		
		StringMatcher matcher = LDMatcher.INSTANCE;
		int tollerance = VODAFONE_TOLLERANCE;
		
		if (userAgent.indexOf("Nokia") != -1) {
			
			tollerance = StringUtils.indexOfOrLength(userAgent, "/", StringUtils.indexOfOrLength(userAgent, "Nokia"));
			matcher = RISMatcher.INSTANCE;
		}
		
		if(logger.isDebugEnabled()){
			
			StrBuilder logBuilder = new StrBuilder();
			logBuilder.append("Applying ");
			
			logBuilder.append(matcher);
			logBuilder.append(tollerance).append(") UA: ");
			logBuilder.append(userAgent);
		}
		
		
		match = matcher.match(userAgentsSet, userAgent, tollerance);
		
		return match;
	}
}
